package com.yc.pre.controller;

import com.alibaba.fastjson.JSON;
import com.yc.pre.entity.PreUserJwtRes;
import com.yc.pre.entity.Result;
import com.yc.pre.entity.StatusCode;
import com.yc.pre.entity.dto.CaptchaDetail;
import com.yc.pre.entity.dto.PreLoginResponse;
import com.yc.pre.entity.vo.EditPasswordRequest;
import com.yc.pre.entity.vo.UserLoginVo;
import com.yc.pre.service.PreSignUserService;
import com.yc.pre.utils.RedisUtil;
import com.yc.pre.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @ClassName IndexController
 * @Description 无需权限，放行接口
 * @Date 2021/02/10 13:52:33
 * @Created by ccc-j
 * @email ccc-ju@outlook.com
 */
@RestController
@RequestMapping("/api/index")
@Api(value = "登录模块接口",tags = "登录模块接口")
public class IndexController {

    @Autowired
    private PreSignUserService preSignUserService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    @ApiOperation(value = "登录模块-->用户登录", notes = "登录模块-->用户登录")
    public Result<PreUserJwtRes> login(@RequestBody UserLoginVo userLoginVo) {
        Boolean aBoolean = userLoginVo.checkParam();
        if (!aBoolean) {
            return new Result(StatusCode.PARAM_ERROR, "param error, please check input params!", null);
        }
        // 判断当前帐号是否密码错误超过两次，超过两次，第三次则需要验证码
        String errorCount = (String) redisTemplate.opsForValue().get("COUNT_ERROR_" + userLoginVo.getPhone());
        // 不需要验证码的情况
        if (ObjectUtils.isEmpty(errorCount) || Integer.parseInt(errorCount) <= 2) {
            // 说明账号的错误次数不存在或者小于3
            PreUserJwtRes result = preSignUserService.login(userLoginVo);
            redisTemplate.delete("COUNT_ERROR_" + userLoginVo.getPhone());
            return new Result(StatusCode.OK, "success!", result);
        }
        // 需要验证码的情况
        String picCode = (String) redisTemplate.opsForValue().get("PIC_CODE_" + userLoginVo.getPhone());
        // 输入的验证码全转为小写
        picCode = picCode.toLowerCase();
        if (StringUtils.isBlank(userLoginVo.getPicCode())) {
            return new Result(StatusCode.PARAM_ERROR, "param error, please check input params!", null);
        } else if (!userLoginVo.getPicCode().equals(picCode)) {
            return new Result(StatusCode.CODE_ERROR, "code error, please check input code!", null);
        } else {
            // 登录成功，直接删除账号的错误次数
            PreUserJwtRes result = preSignUserService.login(userLoginVo);
            redisTemplate.delete("COUNT_ERROR_" + userLoginVo.getPhone());
            return new Result(StatusCode.OK, "success!", result);
        }
    }

    @ApiOperation(value = "预登录检查账号状态", notes = "预登录检查账号状态")
    @GetMapping("/preLogin")
    public Result<PreLoginResponse> preLogin(@RequestParam("phone") @ApiParam(value = "手机号", required = true) String phone){
        return Result.isOk(preSignUserService.preLogin(phone));
    }

    @ApiOperation(value = "获取图片验证码", notes = "获取图片验证码")
    @GetMapping("/getCaptcha")
    public Result<CaptchaDetail> getCaptcha(@RequestParam("phone") @ApiParam(value = "手机号", required = true) String phone){
        return Result.isOk(preSignUserService.getCaptcha(phone));
    }

    @GetMapping("/getUserInfo")
    @ApiOperation(value = "根据手机号获取用户信息", notes = "根据手机号获取用户信息")
    public Result<PreUserJwtRes> getUserInfoFromToken() {
        String jsonStr = (String) redisTemplate.opsForValue().get(RedisUtil.getLoginKey());
        PreUserJwtRes jwtResponse = JSON.parseObject(jsonStr, PreUserJwtRes.class);
        return new Result<>(true, StatusCode.OK, "获取用户信息成功", jwtResponse);
    }

    @PostMapping("/logout")
    @ApiOperation(value = "退出登录")
    public Result logout() {
        redisTemplate.delete(RedisUtil.getLoginKey());
        return Result.isOk();
    }

    @ApiOperation(value = "修改密码")
    @PostMapping("/editPassword")
    public Result editPassword(@RequestBody @Valid EditPasswordRequest request){
        preSignUserService.updatePassword(request, UserUtil.getUserId());
        return Result.isOk();
    }
}
